package edu.ynu.se.xiecheng.achitectureclass.soildata.controller;

import edu.ynu.se.xiecheng.achitectureclass.soildata.service.SoilDataCollectorService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

/**
 * 手动触发数据采集控制器
 */
@Tag(name = "手动数据采集", description = "手动触发数据采集相关接口")
@RestController
@RequestMapping("/api/collector")
@CrossOrigin(originPatterns = "*", allowCredentials = "true")
@RequiresAuthentication
public class ManualDataCollectorController {

    private static final Logger logger = LoggerFactory.getLogger(ManualDataCollectorController.class);
    private final SoilDataCollectorService collectorService;

    @Autowired
    public ManualDataCollectorController(SoilDataCollectorService collectorService) {
        this.collectorService = collectorService;
    }

    /**
     * 手动触发土壤检测数据采集
     *
     * @param greenhouseNumber 大棚编号
     * @return 操作结果
     */
    @Operation(summary = "手动采集数据")
    @PostMapping("/collect/{greenhouseNumber}")
    @RequiresAuthentication
    public ResponseEntity<?> collectData(@PathVariable String greenhouseNumber) {
        try {
            logger.info("开始采集大棚 {} 的数据", greenhouseNumber);
            collectorService.collectAndStoreData(greenhouseNumber);
            return ResponseEntity.ok()
                    .body(Map.of(
                            "success", true,
                            "message", "数据采集成功",
                            "greenhouseNumber", greenhouseNumber
                    ));
        } catch (IllegalArgumentException e) {
            logger.error("数据格式错误: {}", e.getMessage(), e);
            return ResponseEntity.badRequest()
                    .body(Map.of(
                            "success", false,
                            "message", "数据格式错误: " + e.getMessage(),
                            "greenhouseNumber", greenhouseNumber
                    ));
        } catch (Exception e) {
            logger.error("数据采集失败: {}", e.getMessage(), e);
            return ResponseEntity.badRequest()
                    .body(Map.of(
                            "success", false,
                            "message", "数据采集失败: " + e.getMessage(),
                            "greenhouseNumber", greenhouseNumber
                    ));
        }
    }
}
